from PyQt5.QtCore import Qt, QRect, QLine, QPoint, QLineF, QSizeF
from PyQt5.QtGui import QPainter
from PyQt5.QtGui import QPixmap, QFont, QPen, QColor
from PyQt5.QtPrintSupport import QPrinter, QPrintPreviewDialog
from PyQt5.QtWidgets import QMainWindow

from utils.define import WIDTH, HIGH, ITEM, FACTORY
from utils.num2words import num2words


def drawMain(parent: QMainWindow, info, items, fontSize):
    # 这里是设置为600ppi(每英寸像素数) 等同于printer.setResolution(600)
    printer = QPrinter(QPrinter.HighResolution)

    # 175*95: 标准收据纸张大小
    # 241 * 93: 现在使用的大小
    paperSize = QSizeF(241, 93)
    # 设置单位Millimeter毫米  最后相当于设置了一个 4133 * 2242 像素的打印范围
    printer.setPaperSize(paperSize, QPrinter.Millimeter)

    # 弹出打印预览对话框
    preview = QPrintPreviewDialog(printer, parent)

    preview.paintRequested.connect(lambda: drawPic(parent, printer, info, items, fontSize))
    printResult = preview.exec_()

    return printResult == QPrintPreviewDialog.Accepted


def drawPic(parent: QMainWindow, printer, info, items, fontSize):
    pix = QPixmap(WIDTH, HIGH)
    # createPix(pix)
    # 纵向：Portrait 横向：Landscape
    printer.setOrientation(QPrinter.Portrait)

    # 两个begin？？ 搜索一下
    painter = QPainter(parent)

    # viewport 由 printer 设置的参数决定 每英寸像素点数 * printer设置的大小
    painter.begin(printer)
    rect = QRect(painter.viewport())

    x = rect.width() / pix.width()
    y = rect.height() / pix.height()
    painter.scale(x, y)

    drawInvoice(painter, info, items, fontSize)

    # 使用pix创建的模板进行绘制
    # painter.drawPixmap(0, 0, pix)

    painter.end()


def drawInvoice(painter, info, items, fontSize):
    # 表格的基础偏移
    top = 75 + 16 + 8
    left = 100
    right = 1055

    # 高度
    high = 36
    bottom = top + high * 8
    bottomLerp = bottom - high
    # 各列宽度
    name2Width = {"id": 80, "name": 240, "unit": 80, "num": 100, "unitPrice": 100, "price": 150, "note": 200}

    yList = []
    # 每列的左边界
    xDict = {}
    # 每列的右边界
    xrDict = {}

    font = QFont()
    # 调整拉伸因子来改变字符的长度和宽度比例(拉伸因子大于100会增加字符宽度，小于100会减小字符宽度
    # font.setStretch(125)
    font.setFamily("黑体")

    def initPosition():
        sum = left
        for key, value in name2Width.items():
            xDict[key] = sum
            sum = sum + value
            xrDict[key] = sum
        # 包括顶边
        for i in range(0, 9):
            yList.append(i * high + top)

    def drawBase():
        # 框线
        painter.setPen(QPen(QColor(0, 0, 0), 1))
        lines = [

            # 外边框
            QLine(QPoint(left, top), QPoint(right, top)),  # 上边
            QLine(QPoint(right, top), QPoint(right, bottom)),  # 右边
            QLine(QPoint(left, bottom), QPoint(right, bottom)),  # 下边
            QLine(QPoint(left, top), QPoint(left, bottom)),  # 左边

            # 横分割线
            QLine(QPoint(left, yList[1]), QPoint(right, yList[1])),  # 分割出上部信息栏 每列: 40
            QLine(QPoint(left, yList[2]), QPoint(right, yList[2])),
            QLine(QPoint(left, yList[3]), QPoint(right, yList[3])),
            QLine(QPoint(left, yList[4]), QPoint(right, yList[4])),
            QLine(QPoint(left, yList[5]), QPoint(right, yList[5])),
            QLine(QPoint(left, yList[6]), QPoint(right, yList[6])),
            QLine(QPoint(left, yList[7]), QPoint(right, yList[7])),

            # 竖分割线

            QLine(QPoint(xrDict["id"], top), QPoint(xrDict["id"], bottom)),  # 行号 80
            QLine(QPoint(xrDict["name"], top), QPoint(xrDict["name"], bottomLerp)),  # 名称 220
            QLine(QPoint(xrDict["unit"], top), QPoint(xrDict["unit"], bottomLerp)),  # 单位 80
            QLine(QPoint(xrDict["num"], top), QPoint(xrDict["num"], bottomLerp)),  # 数量 100
            QLine(QPoint(xrDict["unitPrice"], top), QPoint(xrDict["unitPrice"], bottom)),  # 单价 100
            QLine(QPoint(xrDict["price"], top), QPoint(xrDict["price"], bottomLerp)),  # 金额 150
            # 备注 265
        ]
        painter.drawLines([QLineF(line) for line in lines])

        # title
        font.setPointSize(fontSize[0])
        font.setLetterSpacing(QFont.PercentageSpacing, 120)  # 设置字间距为150%
        painter.setFont(font)
        painter.drawText(0, 0, WIDTH, top, Qt.AlignCenter, f"{FACTORY}收款收据")

        # 信息栏
        font.setPointSize(fontSize[2])
        # font.setFamily("宋体")
        font.setLetterSpacing(QFont.PercentageSpacing, 0)  # 设置字间距为150%
        painter.setFont(font)
        painter.drawText(xDict["id"], top, name2Width["id"], high, Qt.AlignCenter, "货号")
        painter.drawText(xDict["name"], top, name2Width["name"], high, Qt.AlignCenter, "名称")
        painter.drawText(xDict["unit"], top, name2Width["unit"], high, Qt.AlignCenter, "单位")
        painter.drawText(xDict["num"], top, name2Width["num"], high, Qt.AlignCenter, "数量")
        painter.drawText(xDict["unitPrice"], top, name2Width["unitPrice"], high, Qt.AlignCenter, "单价")
        painter.drawText(xDict["price"], top, name2Width["price"], high, Qt.AlignCenter, "金 额")
        painter.drawText(xDict["note"], top, name2Width["note"], high, Qt.AlignCenter, "备注")

        painter.drawText(xDict["id"], bottomLerp, name2Width["id"], high, Qt.AlignCenter, "总计")
        # painter.drawText(xDict["id"], bottom, name2Width["id"], 25, Qt.AlignLeft | Qt.AlignTop, "手机:")

        painter.drawText(xDict["price"] + 40, bottom, 200, 25, Qt.AlignLeft | Qt.AlignTop, "收货单位:")

    def drawInfo(sumPrice):
        painter.drawText(xDict["unit"], bottom, 200, 25, Qt.AlignLeft | Qt.AlignTop, "收款单位:" + info["money"])

        painter.drawText(left, top - 30, 150, 30, Qt.AlignLeft | Qt.AlignBottom, "客户:" + info["customer"])
        painter.drawText(xDict["id"], bottom, 200, 25, Qt.AlignLeft | Qt.AlignTop, "手机:" + info["mobile"])

        font.setPointSize(fontSize[1])
        painter.setFont(font)
        painter.drawText(xDict["note"], top - 80, name2Width["note"], 25, Qt.AlignRight, "No." + info["id"])
        font.setPointSize(fontSize[2])
        painter.setFont(font)
        painter.drawText(xDict["note"], top - 25, name2Width["note"], 25, Qt.AlignRight | Qt.AlignBottom, info["date"])
        painter.drawText(xDict["name"] + 20, yList[7], name2Width["name"], 40, Qt.AlignLeft | Qt.AlignVCenter,
                         num2words(sumPrice))
        painter.drawText(xDict["price"] + 20, yList[7], name2Width["price"], 40, Qt.AlignLeft | Qt.AlignVCenter,
                         str('%.2f' % sumPrice))
        # print(info)

    def drawItems():
        sumPrice = 0
        # print("drawItems")
        for index, item in enumerate(items):
            # 从第二行开始输入具体内容所以要+1
            y = yList[index + 1]
            for key in ITEM:
                if key == "price":
                    sumPrice += float(item[key])
                # print(xDict[key], y, name2Width[key], high, item[key])
                painter.drawText(xDict[key], y, name2Width[key], high, Qt.AlignCenter, str(item[key]))
        return sumPrice

    # painter = QPainter()
    # painter.begin(pix)
    painter.setRenderHint(QPainter.Antialiasing, True)

    # 设置画笔颜色、宽度
    painter.setPen(QPen(QColor(255, 255, 255), 2))

    # 设置画刷颜色
    painter.setBrush(QColor(255, 255, 255))

    rect = QRect(0, 0, WIDTH, HIGH)
    # 整张图设置画刷白底
    painter.fillRect(rect, QColor(255, 255, 255))
    painter.drawRect(rect)
    initPosition()
    drawBase()
    sumPrice = drawItems()
    drawInfo(sumPrice)
